package com.itheima.travel.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itheima.travel.constant.Constant;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.res.GetwayRespons;
import com.itheima.travel.session.SubjectUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Description：是否登录拦截
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    SubjectUserContext subjectUserContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        boolean isLogin = subjectUserContext.existSubject();
        if (!isLogin) {
            GetwayRespons getwayRespons = GetwayRespons.builder()
                    .code(StatusEnum.NO_LOGIN.getCode())
                    .msg(StatusEnum.NO_LOGIN.getMsg())
                    .data("")
                    .operationTime(new Date())
                    .build();
            response.setContentType("application/json; charset=utf-8");
            //转换json,且处理时间格式
            response.getWriter().write(JSONObject.toJSONString(getwayRespons,
                    SerializerFeature.WriteDateUseDateFormat));
            return false;
        }
        return true;
    }

}
